package utils

import (
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"sync"
)

func MustCopy(dst io.Writer, src io.Reader) {
	_, err := io.Copy(dst, src)
	if err != nil {
		log.Fatal(err)
	}
}

func WalkDir(dir string, wg *sync.WaitGroup, fileSizes chan<- int64) {
	defer wg.Done()
	for _, info := range dirents(dir) {
		if info.IsDir() {
			wg.Add(1)
			fmt.Printf("filename: %s\n", info.Name())
			subDir := filepath.Join(dir, info.Name())
			go WalkDir(subDir, wg, fileSizes)
		} else {
			fileSizes <- info.Size()
		}
	}
}
// 限制goroutine过多
var same = make(chan struct{}, 20)
func dirents(dir string) []os.FileInfo {
	same <- struct{}{} // 获取令牌
	defer func() {
		<-same // 释放令牌
	}()
	readDir, err := ioutil.ReadDir(dir)
	if err != nil {
		fmt.Fprintf(os.Stderr, "du1: %v\n", err)
		return nil
	}
	return readDir
}
